package com.tbrain.secretFriend.service;
import java.sql.*;
import java.util.*;

import com.tbrain.secretFriend.model.User;

public class UserService {
	private Connection conn;

	public UserService(Connection c){
		conn = c;
	}

	public User selectByUserName(String userName){
		User u = null;
		try {
			PreparedStatement p = conn.prepareStatement("SELECT	UserId,UserName,Password,GroupId,SecretFriend FROM SF_USER WHERE UserName= ? ");
			p.setString(1, userName);
			ResultSet r = p.executeQuery();
			if(r.next()){
				u = new User();
				u.setUserId(r.getInt(1));
				u.setUserName(r.getString(2));
				u.setPassword(r.getString(3));
				u.setGroupId(r.getInt(4));
				u.setSecretFriend(r.getInt(5));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return u;
	}

	public boolean isValidUser(User user,String password)throws SecretFriendException{
		if(user==null){
			throw new SecretFriendException("El Usuario No Existe");
		}
		if(password==null || password.trim().equals("")){
			throw new SecretFriendException("La Contrasena no deber estar en blanco");
		}
		if(user.getPassword()==null || user.getPassword().trim().equals("")){
			user.setPassword(password);
			updatePassword(user);
		}
		if(!user.getPassword().equalsIgnoreCase(password)){
			throw new SecretFriendException("La Contrasena de Usuario ["+user.getUserName()+"] no es Valida");
		}
		return true;
	}

	public List selectUsersNotInGroup(int groupId){
		List list = new ArrayList();
		try {
			PreparedStatement p = conn.prepareStatement("SELECT UserId,UserName,Password,GroupId,SecretFriend FROM SF_USER WHERE GroupId <> ? ");
			p.setInt(1, groupId);
			ResultSet r = p.executeQuery();
			while(r.next()){
				User u = new User();
				u.setUserId(r.getInt(1));
				u.setUserName(r.getString(2));
				u.setPassword(r.getString(3));
				u.setGroupId(r.getInt(4));
				u.setSecretFriend(r.getInt(5));
				list.add(u);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	public List selectUsers(){
		List list = new ArrayList();
		try {
			PreparedStatement p = conn.prepareStatement("SELECT UserId,UserName,Password,GroupId,SecretFriend FROM SF_USER");
			ResultSet r = p.executeQuery();
			while(r.next()){
				User u = new User();
				u.setUserId(r.getInt(1));
				u.setUserName(r.getString(2));
				u.setPassword(r.getString(3));
				u.setGroupId(r.getInt(4));
				u.setSecretFriend(r.getInt(5));
				list.add(u);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	public List selectUsersAvailables(User user){
		List users = selectUsersNotInGroup(user.getGroupId());
		List allUsers = selectUsers();
		List list = new ArrayList();
		for(int i=0;i<users.size();i++){
			User u = (User)users.get(i);
//			System.out.println("\tUsuario:"+u);

			if(u.getGroupId()!=user.getGroupId()){
				boolean assigned=false;
				for(int j=0;j<allUsers.size();j++){
					User allUser = (User)allUsers.get(j);
					if(allUser.getSecretFriend()==u.getUserId()){
						assigned=true;
					}
				}
				if(!assigned){
					System.out.println("\t\tUsuario en lista:"+u);
					list.add(u);
				}
			}
		}
		return list;
	}

	public boolean updateSecretFiend(User user){
		try {
			PreparedStatement p = conn.prepareStatement("UPDATE SF_USER SET SecretFriend = ? WHERE UserId= ? ");
			p.setInt(1, user.getSecretFriend());
			p.setInt(2, user.getUserId());
			int value = p.executeUpdate();
			if(value>0){
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean updatePassword(User user){
		try {
			PreparedStatement p = conn.prepareStatement("UPDATE SF_USER SET Password = ? WHERE UserId= ? ");
			p.setString(1, user.getPassword());
			p.setInt(2, user.getUserId());
			int value = p.executeUpdate();
			if(value>0){
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean clearSecretFriend(){
		try {
			System.out.println("********* CLEAR ************");
			PreparedStatement p = conn.prepareStatement("UPDATE SF_USER SET SecretFriend = ?");
			p.setInt(1, 0);
			int value = p.executeUpdate();
			if(value>0){
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	private void calculateSecretFriend(User user){
		List availables = selectUsersAvailables(user);
		Collections.shuffle(availables);
		for(int i=0;i<availables.size();i++){
			User u = (User)availables.get(i);
			user.setSecretFriend(u.getUserId());
		}
	}

	public void calculateAllSecretFriend(){
		boolean allSuccess=false;
		while(!allSuccess){
			List users = selectUsers();
			for(int i=0;i<users.size();i++){
				User u = (User)users.get(i);
				User secret = selectSecretFriend(u);
				System.out.print(u+"\t--->");
				System.out.println(secret);
			}
			for(int i=0;i<users.size();i++){
				User u = (User)users.get(i);
				if(u.getSecretFriend()==0){
					allSuccess=false;
					clearSecretFriend();
					break;
				}else{
					allSuccess=true;
				}
			}
		}
	}

	public User selectSecretFriend(User user){
		User u = null;
		try {
			if(user.getSecretFriend()==0){
				calculateSecretFriend(user);
				updateSecretFiend(user);
			}
			PreparedStatement p = conn.prepareStatement("SELECT	UserId,UserName,Password,GroupId,SecretFriend FROM SF_USER WHERE UserId= ? ");
			p.setInt(1, user.getSecretFriend());
			ResultSet r = p.executeQuery();
			if(r.next()){
				u = new User();
				u.setUserId(r.getInt(1));
				u.setUserName(r.getString(2));
				u.setPassword(r.getString(3));
				u.setGroupId(r.getInt(4));
				u.setSecretFriend(r.getInt(5));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return u;
	}

}

